package biz.noip.strategy.util;

import org.andengine.extension.tmx.TMXLayer;
import org.andengine.extension.tmx.TMXTile;
import org.andengine.util.algorithm.path.ICostFunction;
import org.andengine.util.algorithm.path.IPathFinderMap;
import org.andengine.util.algorithm.path.Path;
import org.andengine.util.algorithm.path.astar.AStarPathFinder;
import org.andengine.util.algorithm.path.astar.NullHeuristic;

import biz.noip.strategy.scenes.GameScene;

public class PathGenerator {

	private Path mAStarPath;
	private AStarPathFinder<TMXLayer> mAStar;
	private IPathFinderMap<TMXLayer> mPathMap;
	private NullHeuristic<TMXLayer> mHeuristic;
	private ICostFunction<TMXLayer> mCostFunction;
	private GameScene mScene;
	private TMXLayer mTMXMapLayer;

	public PathGenerator(GameScene pScene, TMXLayer pTMXMapLayer) {
		this.mScene = pScene;
		this.mTMXMapLayer = pTMXMapLayer;
		this.mAStar = new AStarPathFinder<TMXLayer>();
		this.mHeuristic = new NullHeuristic<TMXLayer>();
		this.mCostFunction = new ICostFunction<TMXLayer>() {

			public float getCost(IPathFinderMap<TMXLayer> pPathFinderMap, int pFromX, int pFromY, int pToX, int pToY,
					TMXLayer pEntity) {
				return 1;
			}
		};
		this.mPathMap = new IPathFinderMap<TMXLayer>() {

			public boolean isBlocked(int pX, int pY, TMXLayer pEntity) {
				for (TMXTile tile : mScene.getListWalls()) {
					if (pX == tile.getTileColumn() && pY == tile.getTileRow()) {
						return true;
					}
				}
				return false;
			}
		};
	}

	public boolean isMoveable(int pFromX, int pFromY, int pToX, int pToY, int move) {
		mAStarPath = this.mAStar.findPath(this.mPathMap, 0, 0, mTMXMapLayer.getTileColumns(),
				mTMXMapLayer.getTileRows(), mTMXMapLayer, pFromX, pFromY, pToX, pToY, false, this.mHeuristic,
				this.mCostFunction);
		if (mAStarPath == null) {
			return false;
		}
		if (mAStarPath.getLength() > move) {
			return false;
		}
		return true;
	}

	public Path getPath(int pFromX, int pFromY, int pToX, int pToY) {
		return this.mAStar.findPath(this.mPathMap, 0, 0, mTMXMapLayer.getTileColumns(), mTMXMapLayer.getTileRows(),
				mTMXMapLayer, pFromX, pFromY, pToX, pToY, false, this.mHeuristic, this.mCostFunction);
	}
}
